package lesson07.threadpool;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 自定义一个线程池
 *
 * @author wileda
 * @date 2023/01/15  12:32
 */
public class MyThreadPool {
        //使用一个阻塞队列来管理任务
        BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

        public void submit(Runnable runnable) throws InterruptedException {
            queue.put(runnable);
        }

    public MyThreadPool(int num) {
        if(num <= 0){
            throw new RuntimeException("创建线程数不能小于0");
        }
        for (int i = 0; i < num; i++) {
            Thread thread = new Thread(() ->{
                while (true){
                    try {
                        Runnable result = queue.take();
                        result.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool = new MyThreadPool(5);
        for (int i = 0; i < 100; i++) {
            int taskId = i;
            myThreadPool.submit(() -> {
                System.out.println("线程" + taskId + " " +Thread.currentThread().getName());
            });
        }
    }
}
